//

//  YDInOptionsViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2018/3/2.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDInOptionsViewController.h"
#import "YDInOptionsCell.h"
#import "YDInOptionsModel.h"
#import "YDBuyOptionsViewController.h"

@interface YDInOptionsViewController ()<UITableViewDelegate , UITableViewDataSource , SYNoDataViewDelegate , SYInOptionsCellDelegate>


@property (nonatomic , weak) UITableView *tableView;


@property (nonatomic , strong) NSMutableArray *modelArray;

//当前页码
@property (nonatomic , assign) NSInteger currentPage;

//无数据
@property (nonatomic , weak) SYNoDataView *dataView;
//网络占位图
@property (nonatomic, weak) SYNoNetView *noNetView;

//引导登录页
@property (nonatomic, weak) SYGuideLoginView *guideLoginView;

//顶部安全区域
@property (nonatomic , assign) CGFloat safeTopH;
//底部安全区域
@property (nonatomic , assign) CGFloat safeBottomH;


@end

@implementation YDInOptionsViewController

-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    self.safeTopH = isPhoneX ? 84 : 64;
    self.safeBottomH = self.isHiddenTabbar ? 0 : (isPhoneX ? 83 : 49);
    [self tableView];    
    [self setUpDataManger];
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([SYUserInformation sharedInstance].isLogin)
    {
        [self loadData];
        [self.guideLoginView removeFromSuperview];
    }else{
        [self.modelArray removeAllObjects];
        [self.tableView reloadData];
        [self guideLoginView];
    }
}
- (void)removeNoNetView
{
    if (_noNetView != nil) {
        [_noNetView removeFromSuperview];
        _noNetView = nil;
    }
}

- (void)removeNodataView
{
    if (_dataView != nil) {
        [_dataView removeFromSuperview];
        _dataView = nil;
    }
}


-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    header.lastUpdatedTimeLabel.hidden = YES ;
    header.stateLabel.hidden = YES ;
    header.label.hidden = YES;
    self.tableView.mj_header = header;
//    [self.tableView.mj_header beginRefreshing];
    
    
    MJGIFFooter *footer = [MJGIFFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}
//加载数据
-(void)loadData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:OptionsInPositionReword WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [self.tableView.mj_header endRefreshing];
        DDLog(@"resultDict = %@" , resultDict)
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.modelArray removeAllObjects];
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            self.modelArray = [YDInOptionsModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            if (self.modelArray.count <10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            if (self.modelArray.count) {
                [self removeNoNetView];
                [self removeNodataView];
                
                
            }else{
                [self removeNoNetView];
                [self removeNodataView];
                [self dataView];
                self.tableView.mj_footer.hidden = YES;
            }
            
            
            
            
            [self.tableView reloadData];
            
            
        }else{
            
            self.tableView.mj_footer.hidden = YES;
            
            if (self.modelArray.count) {
                [self.modelArray removeAllObjects];
                [self.tableView reloadData];
            }
            [self removeNoNetView];
            [self removeNodataView];
            [self noNetView];
            
        }
  
    } failBlock:^(NSError *error) {
        
        
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = YES;
        [self.tableView.mj_header endRefreshing];
       
        if (self.modelArray.count) {
//            [self.modelArray removeAllObjects];
//            [self.tableView reloadData];
        }else
        {
//            [self removeNoNetView];
            [self removeNodataView];
            
            [self noNetView];
        }
      
        
        
    }];
}
//加载更多
-(void)loadMoreData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:OptionsInPositionReword WithSuccessBlock:^(NSDictionary *resultDict) {
        //        DDLog(@"resultDict%@",resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            
            NSArray *array = [YDInOptionsModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            [self.modelArray addObjectsFromArray:array];
            
            [self.tableView reloadData];
            
            if (array.count <10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            
        }else{
            [[SYProgressHUD sharedInstance] showSVOnlytextWithText:@"加载出错"];
            [[SYProgressHUD sharedInstance] dismissSVWithTime:1];
            [self.tableView.mj_footer endRefreshing];
            
        }
    } failBlock:^(NSError *error) {
        //        DDLog(@"%@",error)
        [[SYProgressHUD sharedInstance] showSVOnlytextWithText:@"加载出错"];
        [[SYProgressHUD sharedInstance] dismissSVWithTime:1];
        [self.tableView.mj_footer endRefreshing];
    }];
}
/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.safeTopH - self.safeBottomH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDInOptionsModel *model = self.modelArray[indexPath.row];
    if (model.isSelected) {
        return isPhoneX ? rateX812(206) : rate750(206);
    }else{
        return isPhoneX ? rateX812(160) : rate750(160);
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDInOptionsCell *cell = [YDInOptionsCell cellWithTableView:tableView];
    cell.delegate = self;
    YDInOptionsModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    

}
/*******dataView********/
-(SYNoDataView *)dataView
{
    if (_dataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(276) : rate750(276);
        CGFloat dataY = isPhoneX ? rateX812(100) : rate750(100);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        //wuneirong   wuxinhao
        SYNoDataView *dataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"策略申购" IsCanSeeBuyButton:YES];
        dataView.delegate = self;
        dataView.isCanSeeBuyButton = YES;
        [self.tableView addSubview:dataView];
        _dataView = dataView;
    }
    return _dataView;
}
#pragma SYNoDataViewDelegate
-(void)noDataView:(SYNoDataView *)noDataView didClickSaleButton:(SYNoHeightedButton *)button
{
    YDBuyOptionsViewController *vc = [[YDBuyOptionsViewController alloc] init];
    vc.stockCode = @"000001";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    DDLog(@"期权持仓界面期权交易")
}
-(void)inOptionsCellDidClickOpenButton:(YDInOptionsCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YDInOptionsModel *model = self.modelArray[indexPath.row];
    model.isSelected = !model.isSelected;
    
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
}
-(SYNoNetView *)noNetView
{
    if (_noNetView == nil) {
        SYNoNetView *noNetView = [[SYNoNetView alloc] init];
        [self.tableView addSubview:noNetView];
        
        [noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [noNetView setClickBlock:^(BOOL isClick) {
            [weself.tableView.mj_header beginRefreshing];
            
        }];
        _noNetView = noNetView;
    }
    return _noNetView;
}
-(SYGuideLoginView *)guideLoginView
{
    if (_guideLoginView == nil) {
        //没有登录贴引导登录展位图
        SYGuideLoginView *guideLoginView = [[SYGuideLoginView alloc] init];
        [self.view addSubview:guideLoginView];
        [guideLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [guideLoginView setClickBlock:^(BOOL isClick) {
            YDLoginController *loginVC = [[YDLoginController alloc] init];
            loginVC.loginStyle = Login_Present;
            YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
            [weself presentViewController:baseNav animated:YES completion:nil];
        }];
        _guideLoginView = guideLoginView;
    }
    return _guideLoginView;
}


#pragma SYInOptionsCellDelegate
-(void)inOptionsCellDidClickSaleButton:(YDInOptionsCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YDInOptionsModel *model = self.modelArray[indexPath.row];
    
    //获取买入时间及过期时间
    NSString *beginTime = model.buyingTime;
    NSString *expireTime = model.expireTime;
    
    
    if (!beginTime.length || !expireTime.length)return;
    LK(weakSelf)
    //获取系统最新时间
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetSystemNewTime WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200) {
            
            NSString *endTime = [NSString stringWithFormat:@"%@" , resultDict[@"result"]];
            
            //获取剩余天数
            NSInteger day = [NSDate computationalTimeWithBeginTime:endTime andEndTime:expireTime];
            if (day < 1) {//不能卖出，弹框提示
                [weakSelf postView];
                return ;
            }else{//可以卖出
                NSString *postString;
                //判断是不是行权日
                BOOL isRightDay = [NSDate isTodayWithTime:model.expireTime];
                if (isRightDay) {//是行权日
                    postString = [NSString stringWithFormat:@"%@" , @"确定是否卖出股票？"];
                }else{
                    //10：00之后发起的，提示“10点之后发起的卖出请求会在下一个交易日开盘卖出，成交价已开盘实际价格为准，是否继续申购？”
                    if (endTime.length) {
                        NSString *sub = [[[endTime componentsSeparatedByString:@" "] lastObject] stringByReplacingOccurrencesOfString:@":" withString:@""];
                        
                        if (sub.doubleValue > 100000) {
                            postString = [NSString stringWithFormat:@"10点之后发起的卖出请求会在下一个交易日开盘卖出，成交价已开盘实际价格为准，确认提前卖出该股票？合约有效期还剩%zd天" , day];
                        }else
                        {
                           postString = [NSString stringWithFormat:@"确认提前卖出该股票？合约有效期还剩%zd天" , day];
                        }
                    }

                }

                PZTipsAlertView *alert = [PZTipsViewManger shareDoubleTipsAlertViewTitle:@"提示" Mesage:postString CancleTitle:@"取消" SureTitle:@"确定" CancleBlock:^{
                    
                    [weakSelf.pz_popupController dismiss];
                    
                } SureBlock:^{
                    [weakSelf.pz_popupController dismiss];
                    [weakSelf saleOptionsWithIndexpath:indexPath];//卖出
                    
                }];
                
                weakSelf.pz_popupController = [[PZPopUpController alloc] init];
                [weakSelf.pz_popupController dropAnimatedWithRotateAngle:70];
                [weakSelf.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
            }
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"网络出错..." isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"网络出错..." isExistNav:YES];
        
    }];
    
}


-(void)postView
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"当天生成的订单，当天无法交易，最快T+1个交易日进行交易" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        [self.navigationController popToRootViewControllerAnimated:NO];
        [self.pz_popupController dismiss];
    }];
    
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:70];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
-(void)saleOptionsWithIndexpath:(NSIndexPath *)indexPath
{
    LK(weakSelf)
    
    YDInOptionsModel *model = self.modelArray[indexPath.row];
    NSString *ID = model.Id;
    NSString *url = [NSString stringWithFormat:@"/stockoptiontrade/userright/%@" , ID];
    
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:POSTMethod];
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        if ([resultDict[@"code"] integerValue] == 200) {//卖出成功
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeSuccess text:@"行权成功，待结算"
                                                          isExistNav:YES];
            model.state = @"APPLYRIGHT";
            //刷新tableView
            [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
            
            
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
        
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"询价失败"
                                                      isExistNav:YES];
    }];
    
    
    
    
    
}
@end
